import React,{useState,useEffect} from 'react'
import { connect } from 'dva'
import { NavBar ,Icon ,List,InputItem, Button, WhiteSpace, Toast,WingBlank} from 'antd-mobile'
import {getCode, changePass} from '@/api/user-api.js'
import './password.less'
function Password(props){
  const {me,dispatch} = props
  const [password, setPassword] = useState("")
  const [code, setCode] = useState('')
  const [phone, setPhone] = useState("")
  const [codeDisabled, setCodeDisabled] = useState(false)//验证码按钮是否可用
  const [loading, setLoading] = useState(false)//保存按钮是否等待状态转圈
  const [codeBtnText, setCodeBtnText] = useState("验证码")
  const handlePasswordChange = (v) =>{
    setPassword(v)
  }
  const handleCodeChange = (v) =>{
    setCode(v)
  }
  const handleSendCode = async () =>{
    //调用定时器
    runInterval();
    //调用验证码接口
    let res = await getCode();
    if(res.data.code == 200){
      Toast.success('验证码：' + res.data.data.code, 3);
    }
  }
  let runInterval = () =>{
    setCodeDisabled(true);//验证码的按钮不可用
    let seconds = 10;//倒计时开始时间
    //为了避免没显示60秒先设置上60秒
    setCodeBtnText(seconds + "");
    //然后再启动定时器
    let interval = setInterval(() => {
      //判断啥时候清除定时器
      if(seconds > 1){
        setCodeBtnText(--seconds + "");
      }else{
        setCodeDisabled(false);//按钮可用
        setCodeBtnText('重新发送');
        clearInterval(interval);
      }
    }, 1000);
  }
  useEffect(() => {
    (async ()=>{
      dispatch({type:'me/getUserInfo'})
    })()
    
  },[])
  useEffect(() => {
    if(me.userInfo){
      setPhone(me.userInfo.phone)
    }
  }, [me.userInfo]);
  const handleSubmit = async () =>{
    let res = await changePass({phone, password, code});
    if(res.data.code == 200){
      Toast.success(res.data.msg, 1,()=>{
        sessionStorage.clear();
        props.history.push('/login')
      });

    }
  }
  return (
    <div className="password-page">
      <NavBar
        mode="light"
        icon={<Icon type="left" />}
        onLeftClick={() => props.history.go(-1)}
      >修改密码</NavBar>
      <List>
        <List.Item extra={me.userInfo.phone}>手机号</List.Item>
        <InputItem style={{textAlign:'right'}}
            type="password" 
            value={password} 
            onChange={handlePasswordChange} 
            placeholder="请输入新密码" clear>密码</InputItem>
        <InputItem 
            style={{textAlign:'right'}}
            value={code}
            onChange={handleCodeChange} 
            extra={
              <Button size="small" 
                      type="primary" 
                      onClick={handleSendCode} 
                      disabled={codeDisabled}>{codeBtnText}</Button>
            }
            placeholder="请输入验证码">验证码</InputItem>
            <WhiteSpace></WhiteSpace>
            <WingBlank>
              <Button type="primary" loading={loading} onClick={handleSubmit}>保存</Button>
            </WingBlank>
      </List>
    </div>
  )
}
export default connect(({me}) => {
  return {me}
})(Password)
